package logic

import (
	"context"
	"errors"
	"goods_srv/models"
	"goods_srv/pkg"

	"goods_srv/goods"
	"goods_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealNameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRealNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealNameLogic {
	return &RealNameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 实名认证
func (l *RealNameLogic) RealName(in *goods.RealNameRequest) (*goods.RealNameResponse, error) {
	// todo: add your logic here and delete this line

	var err error

	var ur models.UserRealName
	ur.UserId = int(in.UserId)
	err = ur.GetUserRealName()
	if err != nil {
		logx.Error("查询用户失败")
		return nil, errors.New("查询用户失败")
	}

	if ur.ID != 0 {
		logx.Error("用户已实名")
		return nil, errors.New("用户已实名")
	}

	//调用封装函数
	if !pkg.RealName(in.IdCard, in.RealName) {
		logx.Error("实名认证失败")
		return nil, errors.New("实名认证失败")
	}

	ur.UserId = int(in.UserId)
	ur.IdCard = in.IdCard
	ur.RealName = in.RealName
	err = ur.Create()
	if err != nil {
		logx.Error("保存认证信息失败")
		return nil, errors.New("保存认证信息失败")
	}

	return &goods.RealNameResponse{}, nil
}
